package LeetCode;

public class LeetCodeMain16 {
    public int islandPerimeter(int[][] grid) {
        int sum=0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j]==1){
                    sum+=4;
                    if (j>0&&grid[i][j-1]==1){
                        sum-=2;
                    }
                    if (i>0&&grid[i-1][j]==1){
                        sum-=2;
                    }
                }
            }
        }
        return sum;
    }
    int count=0;
    public int islandPerimeter1(int[][] grid) {
        int x=0;
        int y=0;
        int flag=0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j]==1){
                    flag=1;
                    x=i;
                    y=j;
                    break;
                }
            }
            if (flag==1){
                break;
            }
        }
        if(x==0&&y==0&&grid[0][0]!=1){
            return 0;
        }
        DFS(grid,x,y);
        return count;
    }
    public void DFS(int[][] grid ,int x,int y){
        if (x<0||x>=grid.length||y<0||y>=grid[x].length||grid[x][y]!=1){
            count++;
            return;
        }
        if (grid[x][y]==2){
            return;
        }
        grid[x][y]=2;
        DFS(grid,x,y-1);
        DFS(grid,x,y+1);
        DFS(grid,x-1,y);
        DFS(grid,x+1,y);
    }
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int oldColor=image[sr][sc];
        defs(image,sr,sc,newColor,oldColor);
        return image;
    }
    public void defs(int[][] image,int x,int y,int newColor,int oldColor){
        if (x<0||x>=image.length||y<0||y>=image[x].length){
            return;
        }
        if (image[x][y]!=oldColor || image[x][y] == newColor){
            return;
        }
        image[x][y]=newColor;

    }
}
